package com.dailyblue.java.spring.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;
import org.apache.ibatis.io.Resources;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.dailyblue.java.spring.mybatis.mapper")
public class MyBatisConfig {

    // 产生数据源
    @Bean
    DruidDataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("a123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClassName(Driver.class.getName());
        return dataSource;
    }
    // 产生会话工厂
    @Bean
    SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssf = new SqlSessionFactoryBean();
        ssf.setDataSource(dataSource);
        // 加载config.xml文件
        Resource resource = new PathMatchingResourcePatternResolver().getResource("config.xml");
        ssf.setConfigLocation(resource);
        // 加载mapper.xml文件
        Resource mapper1 = new PathMatchingResourcePatternResolver().getResource("mapper/DeptMapper.xml");
        ssf.setMapperLocations(mapper1);
        return ssf;
    }

}
